﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.Data;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraCharts;
using System.Data.SqlClient;
using Lists;
using GeneralLibs;
using DevExpress.XtraCharts;

namespace BI
{
    public partial class FrmChartDashBoardBI : DevExpress.XtraEditors.XtraForm
    {
        public FrmChartDashBoardBI()
        {
            InitializeComponent();
        }

        private string _Title = "";
        public string Title
        {
            set
            {
                _Title = value;
            }
            get
            {
                return _Title;
            }
        }

        private void FrmChartDashBoardBI_Load(object sender, EventArgs e)
        {
            ucOneSeriesChartBienDongHangHoa.GenChart("Theo chiều khách hàng", ViewType.Bar, " (ĐV: triệu VNĐ)");
            ucOneSeriesChartBienDongTienMat.GenChart("Theo chiều khách hàng", ViewType.Bar, " (ĐV: triệu VNĐ)");
            ucOneSeriesChartCongNoPhaiThu.GenChart("Theo chiều khách hàng", ViewType.Bar, " (ĐV: triệu VNĐ)");
            ucOneSeriesChartCongNoPhaiTra.GenChart("Theo chiều khách hàng", ViewType.Bar, " (ĐV: triệu VNĐ)");
            ucTwoSeriesChart.GenChart("", "", ViewType.Bar, " (ĐV: triệu VNĐ)");

            if (DesignMode) return;
            cmbKyBaoCao.SelectedIndex = 17;
            //numInterval.Value = 90;
            numInterval.Value = (int)dtNgayKetThuc.DateTime.Subtract(dtNgayBatDau.DateTime).TotalHours / 10;
        }

        private void cmbKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                DateTime ngayBatDau = dtNgayBatDau.DateTime;
                DateTime ngayKetThuc = dtNgayBatDau.DateTime;
                DateTime now = GeneralLibs.CommonLib.GetSystemDateTime();
                switch (cmbKyBaoCao.Text)
                {
                    case "Hôm nay":
                        dtNgayBatDau.Enabled = true;
                        dtNgayKetThuc.Enabled = true;
                        ngayBatDau = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);
                        ngayKetThuc = new DateTime(now.Year, now.Month, now.Day, 23, 59, 59);
                        break;
                    case "Tuần gần nhất":
                        dtNgayBatDau.Enabled = false;
                        dtNgayKetThuc.Enabled = false;
                        ngayBatDau = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0).AddDays(-7);
                        ngayKetThuc = new DateTime(now.Year, now.Month, now.Day, 23, 59, 59);
                        break;
                    case "Tùy chọn":
                        dtNgayBatDau.Enabled = true;
                        dtNgayKetThuc.Enabled = true;
                        ngayBatDau = new DateTime(GeneralLibs.Config.NamTaiChinh, 1, 1);
                        ngayKetThuc = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59);
                        break;
                    case "Cả năm":
                        dtNgayBatDau.Enabled = false;
                        dtNgayKetThuc.Enabled = false;
                        ngayBatDau = new DateTime(GeneralLibs.Config.NamTaiChinh, 1, 1);
                        ngayKetThuc = new DateTime(GeneralLibs.Config.NamTaiChinh, 12, 31, 23, 59, 59);
                        break;
                    case "Quý I":
                        dtNgayBatDau.Enabled = false;
                        dtNgayKetThuc.Enabled = false;
                        ngayBatDau = new DateTime(GeneralLibs.Config.NamTaiChinh, 1, 1);
                        ngayKetThuc = new DateTime(GeneralLibs.Config.NamTaiChinh, 3, 31, 23, 59, 59);
                        break;
                    case "Quý II":
                        dtNgayBatDau.Enabled = false;
                        dtNgayKetThuc.Enabled = false;
                        ngayBatDau = new DateTime(GeneralLibs.Config.NamTaiChinh, 4, 1);
                        ngayKetThuc = new DateTime(GeneralLibs.Config.NamTaiChinh, 6, 30, 23, 59, 59);
                        break;
                    case "Quý III":
                        dtNgayBatDau.Enabled = false;
                        dtNgayKetThuc.Enabled = false;
                        ngayBatDau = new DateTime(GeneralLibs.Config.NamTaiChinh, 7, 1);
                        ngayKetThuc = new DateTime(GeneralLibs.Config.NamTaiChinh, 9, 30, 23, 59, 59);
                        break;
                    case "Quý IV":
                        dtNgayBatDau.Enabled = false;
                        dtNgayKetThuc.Enabled = false;
                        ngayBatDau = new DateTime(GeneralLibs.Config.NamTaiChinh, 10, 1);
                        ngayKetThuc = new DateTime(GeneralLibs.Config.NamTaiChinh, 12, 31, 23, 59, 59);
                        break;
                    default:
                        try
                        {
                            dtNgayBatDau.Enabled = false;
                            dtNgayKetThuc.Enabled = false;
                            string strThang = ((string)cmbKyBaoCao.SelectedItem).Substring(((string)(cmbKyBaoCao.SelectedItem)).LastIndexOf(" "));
                            int thang = int.Parse(strThang);

                            ngayBatDau = new DateTime(GeneralLibs.Config.NamTaiChinh, thang, 1);
                            ngayKetThuc = new DateTime(GeneralLibs.Config.NamTaiChinh, thang,
                                            DateTime.DaysInMonth(GeneralLibs.Config.NamTaiChinh, thang), 23, 59, 59);
                        }
                        catch (Exception ex)
                        {
                            BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
                        }
                        break;
                }
                dtNgayBatDau.DateTime = ngayBatDau;
                dtNgayKetThuc.DateTime = ngayKetThuc;
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
                BasicForms.FrmProgressBar.FinishShowProgress();
            }
        }

        private void btnLoad_Click_1(object sender, EventArgs e)
        {
            BasicForms.FrmProgressBar.StartShowProgress();
            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                DateTime dtPointNeedCalculate = dtNgayBatDau.DateTime;

                numInterval.Value = (int)dtNgayKetThuc.DateTime.Subtract(dtNgayBatDau.DateTime).TotalHours / 10 / 24;
                if ((int)numInterval.Value <= 0) numInterval.Value = 1;
                int total = (int)dtNgayKetThuc.DateTime.Subtract(dtNgayBatDau.DateTime).TotalHours / (int)numInterval.Value;
                int processed = 0;
                ucOneSeriesChartBienDongHangHoa.Data.Clear();
                ucOneSeriesChartBienDongTienMat.Data.Clear();
                ucOneSeriesChartCongNoPhaiThu.Data.Clear();
                ucOneSeriesChartCongNoPhaiTra.Data.Clear();
                ucTwoSeriesChart.Data.Clear();

                //Biến động tiền mặt
                TaiKhoan tk = DanhMucTaiKhoan.Instance.GetBySoHieu("1111");
                while (dtPointNeedCalculate <= dtNgayKetThuc.DateTime)
                {
                    SoDuTaiKhoan soDu = Lists.SoDuTaiKhoan.CalculateFromDB(cmd, dtPointNeedCalculate, tk.ID);
                    DataRow row = ucOneSeriesChartBienDongTienMat.Data.NewRow();
                    row["Series1Name"] = string.Format("{0}/{1}/{2}", dtPointNeedCalculate.Day, dtPointNeedCalculate.Month, dtPointNeedCalculate.Year);
                    row["Series1Value"] = Math.Abs(soDu.DuNo - soDu.DuCo) / 1000000;
                    ucOneSeriesChartBienDongTienMat.Data.Rows.Add(row);

                    dtPointNeedCalculate = dtPointNeedCalculate.AddDays((double)numInterval.Value);
                }
                ucOneSeriesChartBienDongTienMat.GenChart("", ViewType.Area, "", "Office");

                //Biến động giá trị hàng hóa
                dtPointNeedCalculate = dtNgayBatDau.DateTime;
                tk = DanhMucTaiKhoan.Instance.GetBySoHieu("1561");
                while (dtPointNeedCalculate <= dtNgayKetThuc.DateTime)
                {
                    SoDuTaiKhoan soDu = Lists.SoDuTaiKhoan.CalculateFromDB(cmd, dtPointNeedCalculate, tk.ID);
                    DataRow row = ucOneSeriesChartBienDongHangHoa.Data.NewRow();
                    row["Series1Name"] = string.Format("{0}/{1}/{2}", dtPointNeedCalculate.Day, dtPointNeedCalculate.Month, dtPointNeedCalculate.Year);
                    row["Series1Value"] = Math.Abs(soDu.DuNo - soDu.DuCo) / 1000000;
                    ucOneSeriesChartBienDongHangHoa.Data.Rows.Add(row);

                    dtPointNeedCalculate = dtPointNeedCalculate.AddDays((double)numInterval.Value);
                }
                ucOneSeriesChartBienDongHangHoa.GenChart("", ViewType.Area, "", "Metro");

                //Biến động Công nợ phải thu
                dtPointNeedCalculate = dtNgayBatDau.DateTime;
                tk = DanhMucTaiKhoan.Instance.GetBySoHieu("131");
                while (dtPointNeedCalculate <= dtNgayKetThuc.DateTime)
                {
                    SoDuTaiKhoan soDu = Lists.SoDuTaiKhoan.CalculateFromDB(cmd, dtPointNeedCalculate, tk.ID);
                    DataRow row = ucOneSeriesChartCongNoPhaiThu.Data.NewRow();
                    row["Series1Name"] = string.Format("{0}/{1}/{2}", dtPointNeedCalculate.Day, dtPointNeedCalculate.Month, dtPointNeedCalculate.Year);
                    row["Series1Value"] = Math.Abs(soDu.DuNo - soDu.DuCo) / 1000000;
                    ucOneSeriesChartCongNoPhaiThu.Data.Rows.Add(row);

                    dtPointNeedCalculate = dtPointNeedCalculate.AddDays((double)numInterval.Value);
                }
                ucOneSeriesChartCongNoPhaiThu.GenChart("", ViewType.Area, "", "Opulent");

                //Biến động Công nợ phải trả
                dtPointNeedCalculate = dtNgayBatDau.DateTime;
                tk = DanhMucTaiKhoan.Instance.GetBySoHieu("331");
                while (dtPointNeedCalculate <= dtNgayKetThuc.DateTime)
                {
                    SoDuTaiKhoan soDu = Lists.SoDuTaiKhoan.CalculateFromDB(cmd, dtPointNeedCalculate, tk.ID);
                    DataRow row = ucOneSeriesChartCongNoPhaiTra.Data.NewRow();
                    row["Series1Name"] = string.Format("{0}/{1}/{2}", dtPointNeedCalculate.Day, dtPointNeedCalculate.Month, dtPointNeedCalculate.Year);
                    row["Series1Value"] = Math.Abs(soDu.DuNo - soDu.DuCo) / 1000000;
                    ucOneSeriesChartCongNoPhaiTra.Data.Rows.Add(row);

                    dtPointNeedCalculate = dtPointNeedCalculate.AddDays((double)numInterval.Value);
                }
                ucOneSeriesChartCongNoPhaiTra.GenChart("", ViewType.Area, "", "Flow");

                //Doanh số/Lãi lỗ
                Guid taiKhoanDoanhThuID = (Guid)DanhMucCauHinhTaiKhoanMacDinh.Instance.GetTaiKhoanIDByTinhChat("DoanhThuBanHangVaCungCapDichVu");
                dtPointNeedCalculate = dtNgayBatDau.DateTime;
                ucTwoSeriesChart.Data.Rows.Clear();
                while (dtPointNeedCalculate <= dtNgayKetThuc.DateTime)
                {
                    DataRow row = ucTwoSeriesChart.Data.NewRow();
                    row["Series1Name"] = string.Format("{0}/{1}/{2}", dtPointNeedCalculate.Day, dtPointNeedCalculate.Month, dtPointNeedCalculate.Year);
                    decimal phatSinh = TaiKhoan.TinhSoPhatSinhCo(cmd, taiKhoanDoanhThuID, dtPointNeedCalculate, dtPointNeedCalculate.AddDays(1));
                    row["Series1Value"] = phatSinh / 1000000;

                    row["Series2Name"] = string.Format("{0}/{1}/{2}", dtPointNeedCalculate.Day, dtPointNeedCalculate.Month, dtPointNeedCalculate.Year);
                    cmd.CommandText = "SELECT SUM(Value5 - Value3) AS Lai\n" +
                                        "FROM KhoanMucChungTu \n" +
                                        "WHERE ChungTuID IN (SELECT ChungTuID FROM ChungTu  \n" +
                                        "					WHERE ChungTuGocID IN (SELECT ChungTuID \n" +
                                        "											FROM ChungTu \n" +
                                        "											WHERE LoaiChungTuID IN (SELECT ID FROM LoaiChungTu \n" +
                                        "																	WHERE Ma IN (N'HoaDonBanHang', N'HoaDonBanLe') \n" +
                                        "																	) \n" +
                                        "                                                   AND @ThoiDiemDau <= Ngay AND Ngay <= @ThoiDiemCuoi AND GhiSo = 1\n" +
                                        "											)\n" +
                                        "                   )";
                    cmd.Parameters.Clear();
                    cmd.Parameters.AddWithValue("ThoiDiemDau", dtPointNeedCalculate);
                    cmd.Parameters.AddWithValue("ThoiDiemCuoi", dtPointNeedCalculate.AddDays(1));
                    SqlDataReader dr = cmd.ExecuteReader();
                    if (dr.Read())
                    {
                        if (dr["Lai"] is decimal)
                            row["Series2Value"] = (decimal)dr["Lai"] / 1000000;
                        else
                        {
                            object abc = dr["Lai"];
                            string teyp = abc.GetType().ToString();
                            row["Series2Value"] = (decimal)0;
                        }
                    }
                    dr.Close();


                    ucTwoSeriesChart.Data.Rows.Add(row);
                    dtPointNeedCalculate = dtPointNeedCalculate.AddDays((int)numInterval.Value);
                }
                ucTwoSeriesChart.GenChart("Doanh số", "Lãi", ViewType.Bar, "Doanh số theo ngày (đv: triệu VNĐ)", "In A Fog");
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
            }

            BasicForms.FrmProgressBar.FinishShowProgress();
        }
    }
}
